import {getUsername} from "./utils.js"
import {getRole} from "./utils.js"

/**
 * 获取新闻列表
 */
function getNewsList() {
    const search_content = $(".search-content")
    let search
    if (search_content.val() && search_content.val() !== "") {
        search = search_content.val()
    } else {
        search = ""
    }
    $.ajax({
        url: "http://www.woniu-news.com:8082/getNewsList.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            search: search
        },
        dataType: "json",
        success: (resp) => {
            let context = ""
            if (resp.code === 200) {
                for (let item of resp.data) {
                    context += `
                            <li>
                                <div class="news-title">${item.title}</div>
                                <div class="news-summary">${item.context.substring(0, 10)}...</div>
                                <a href="news_detail.html?nid=${item.id}">阅读详情</a>
                            </li>
                        `
                }
            } else if (resp.code === 202) {
                context = `
                        <li>
                            <div class="news-summary">暂无数据</div>
                        </li>
                    `
            }
            $(".news-list").html(context)
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function setUsername() {
    const username = getUsername()
    if (username) {
        $(".username").text(username)
    }
}

/**
 * 动态设置显示的标签
 */
function setTags() {
    let tags = ""
    if (getUsername()) {
        const login_btn = $(".login-btn")
        login_btn.text("登出")
        login_btn.attr("onclick", "window.location.href='logout.html'")
    }
    if (getRole() === "admin") {
        tags = `
        <a href="post_news.html">发布新闻</a>
        <a href="news_management.html">新闻管理</a>
        <a href="review_management.html">评论管理</a>
        <a href="file_management.html">文件管理</a>
        <a href="user_management.html">用户管理</a>
        <a href="log.html">日志查看</a>`
    } else if (getRole() === "user") {
        tags = `
        <a href="post_news.html">发布新闻</a>
        <a href="file_management.html">文件管理</a>`
    }
    $(".tags").html(tags)
}

getNewsList()
setUsername()
setTags()

// 搜索按钮点击监听器
$(".search").click(() => {
    getNewsList()
})

// 搜索表单回车监听器
$('form').on('submit', function (event) {
    event.preventDefault(); // 阻止任何形式提交刷新页面
    getNewsList();
})